package cz.cernilovsky.android.profileapp.services;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONException;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationStatusCodes;
import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;

import cz.cernilovsky.android.profileapp.R;
import cz.cernilovsky.android.profileapp.activities.MainActivity;
import cz.cernilovsky.android.profileapp.model.Location;
import cz.cernilovsky.android.profileapp.storage.LocationsStorage;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;

public class LoadGeofencesService extends Service implements ConnectionCallbacks, OnConnectionFailedListener, OnAddGeofencesResultListener {
	private LocationClient c;
	private Location[] locations;
	private static final String TAG = "LoadGeofencesService";
	
	@Override
	public IBinder onBind(Intent intent) {
		//connect();
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		//connect();
		//Log.d(TAG, "onStartCommand");
		return START_NOT_STICKY;
		//return super.onStartCommand(intent, flags, startId);
	}
	
	private void connect() {
		c = new LocationClient(getApplicationContext(), LoadGeofencesService.this, LoadGeofencesService.this);
		c.connect();
	}

	@Override
	public void onConnectionFailed(ConnectionResult result) {
		quit();
		NotificationService.notify(getApplicationContext(), R.string.connection_failed, R.string.error);
		Log.e(TAG, "Connection failed");
	}

	private void quit() {
		//Log.d(TAG, "quit()");
		Intent i = new Intent(this, MonitorGeofencesService.class);
		stopService(i);
		c.disconnect();
	}

	@Override
	public void onConnected(Bundle arg0) {
		try {
			locations = LocationsStorage.loadLocations(getApplicationContext());
			List<Geofence> geofences = LocationsStorage.loadGeofences(locations, getApplicationContext());
			if(geofences != null) {
				Intent intent = new Intent(getApplicationContext(), ProfileProcessor.class);
				c.addGeofences(geofences, PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT), LoadGeofencesService.this);
				//Log.d(TAG, "adding geofences");
			} else {
				//Preferences.resetLocationIDs(getApplicationContext());
				NotificationService.mainNotification(getApplicationContext());
				//Log.d(TAG, "geofences null");
				stopSelf();
			}
		} catch (IOException e) {
			NotificationService.notifySettingsIOError(getApplicationContext());
			e.printStackTrace();
		} catch (JSONException e) {
			NotificationService.notifySettingsJSONError(getApplicationContext());
			e.printStackTrace();
		}
	}
	
	@Override
	public void onDisconnected() {
		quit();
		NotificationService.notify(getApplicationContext(), R.string.error_location_service_disconnected, R.string.error);
		Log.e(TAG, "Location service disconnected");
	}

	@Override
	public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {
		if(statusCode == LocationStatusCodes.SUCCESS) {
			Set<String> locationIDs = new HashSet<String>();
			for(String s : geofenceRequestIds) {
				locationIDs.add(s);
			}
			//Preferences.setLoadedLocationIDs(getApplicationContext(), locationIDs);
			NotificationService.mainNotification(getApplicationContext());
			//Log.d(TAG, "Geofences successfully added");
		} else {
			NotificationService.notify(getApplicationContext(), getString(R.string.could_not_load_geofences) + ", status code: " + statusCode, R.string.error);
		}
		
		c.disconnect();
		stopSelf();
	}

	@Override
	public void onCreate() {
		//Log.d(TAG, "onCreate");
		connect();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		//Log.i(TAG, "Destroyed");
		super.onDestroy();
	}
	
}